//------------------------------------------------------------------------------
// X2TK Graphic Toolkit
// Copyright (C) 2006-2007 Janusz Kowalski
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------

#include "SDL.h"

#include "x2tk.h"

#include "x2tk_TextField.h"

// It shouldn't be here.
#include "global.h"

namespace x2tk {

TextField::TextField(int x, int y, int w, int h) : Widget(x,y,w,h), 
font_(X2D_PATH_FONT "HiTechFont_White.png") {
  i_=0; d_=0;
  text_.add(0);
  dalign();
}

void TextField::event_key(const SDL_KeyboardEvent& key) {
  if(key.type==SDL_KEYDOWN) {
    switch(key.keysym.sym) {
      case SDLK_BACKSPACE: {
        if(i_>0) {
          text_.removeElementAt(i_-1); i_--;
        }
      } break;
      case SDLK_DELETE: {
        if(i_<text_.size()-1) text_.removeElementAt(i_);
      } break;
      case SDLK_LEFT: {
        if(i_>0) i_--;
      } break;
      case SDLK_RIGHT: {
          if(i_<text_.size()-1) i_++;
      } break;
      case SDLK_HOME: {
        i_=0;
      } break;
      case SDLK_END: {
        i_=text_.size()-1;
      } break;
      default: {
        Uint16 ch = key.keysym.unicode;
        if(ch!=0) {
          if(!(ch&0xFF00)) {
            text_.insertElementAt(char(ch),i_); i_++;
          }
        }
      } break;
    }
    dalign();
  }
}

bool TextField::mouseDown(int type) {
  int x = getMouseX(), y = getMouseY();
  if(x>=0 && x< getW() && y>=0 && y< getH()) {
    i_=(x+d_+16/2)/16;
    if(i_<0) i_=0; else if(!(i_<text_.size()-1)) i_=text_.size()-1;
  }
  return Widget::mouseDown(type);
}

void TextField::event(EV ev) {
  if(ev==EV_FOCUS) {
    if(hasFocus()) {
      SDL_EnableUNICODE(1);
      SDL_EnableKeyRepeat(250,50);
    } else {
      SDL_EnableUNICODE(0);
      SDL_EnableKeyRepeat(0,0);
    }
  }
  Widget::event(ev);
}

void TextField::draw(GraphicContext &g) {
  g.colorFill(0xff, 0xff, 0xff);
  if(hasFocus()) g.colorFill(0x7f,0x7f,0x7f, 1, 1, getW()-2, getH()-2);
  else g.colorFill(0,0,0, 1, 1, getW()-2, getH()-2);
  
  int dy = (getH()-16)/2;
  
  font_.drawText(g, 1-d_, dy, &text_[0]);
  
  // Draw cursor
  g.colorFill(0xff,0xff,0xff,16*i_-1-d_,dy,2,16);
}

TextField::~TextField() { }

} // namespace x2tk
